package net.synck.gcontacts.editor;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.statushandlers.StatusManager;

import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.util.ServiceException;

public class ContactMultiPageEditor extends FormEditor {
		
	
	private EditorMainPage mainPage = null;
		
	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		if (input instanceof ContactEditorInput) {			
			try {
				((ContactEditorInput)input).checkoutContact(null);
			} catch (IOException e) {
				throw new PartInitException("can not load contact",e); 
			} catch (ServiceException e) {
				throw new PartInitException("can not load contact",e);
			}			
		}
		super.init(site, input);
	}

	@Override
	protected void addPages() {
		
		try {
			mainPage = new EditorMainPage(this,"main","Main");
			addPage(mainPage);
		}
		catch (PartInitException e) {
		//
		}
	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		
		mainPage.doSave(monitor);
					
		try {
			monitor.beginTask("updating contact data", monitor.UNKNOWN);
			((ContactEditorInput)getEditorInput()).commitContact(monitor);
			
			//TODO setPartName
		} catch (MalformedURLException e) {
			monitor.setCanceled(true);
			reportException("can not save contact", e);			

		} catch (IOException e) {

			monitor.setCanceled(true);
			reportException("can not save contact", e);

		} catch (ServiceException e) {

			monitor.setCanceled(true);
			reportException("can not save contact", e);

		} finally {
			monitor.done();
		}
		
		if (!monitor.isCanceled())
			editorDirtyStateChanged();
		
	}

	@Override
	public void doSaveAs() {
	}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}

	
	private ContactEditorInput getContactInput() {
		return (ContactEditorInput)getEditorInput();
	}
	
		
	private void reportException(String message, Throwable e) {
		IStatus status = new Status(IStatus.ERROR, net.synck.gcontacts.Activator.PLUGIN_ID, 1, message, e);		
		//ErrorDialog.openError(this.getSite().getShell(),message, null,status);
		StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.BLOCK);
		e.printStackTrace();
	}
}
